//
//  SEGAuthCodeView.m
//  SEGUhomeStandard
//
//  Created by 乔杨 on 2019/4/9.
//  Copyright © 2019 刘山. All rights reserved.
//

#import "SEGAuthCodeView.h"
#import "SEGRequestManager.h"
#import <Commom/UITextField+Limit.h>

@interface SEGAuthCodeView ()<UITextFieldDelegate>

/** 背景图 */
@property (nonatomic, strong) UIView *bgView;
/** 标题Lab */
@property (nonatomic, strong) UILabel *titleLab;
/** 关闭按钮 */
@property (nonatomic, strong) UIButton *closeBtn;
/** 验证码图片 */
@property (nonatomic, strong) UIButton *codeImg;
/** 刷新按钮 */
@property (nonatomic, strong) UIButton *refreshBtn;
/** line1 */
@property (nonatomic, strong) UIView *line1;
/** 输入框 */
@property (nonatomic, strong) UITextField *codeTF;
/** line2 */
@property (nonatomic, strong) UIView *line2;
/** 下一步按钮 */
@property (nonatomic, strong) UIButton *nextBtn;

/** 请求Manager */
@property (nonatomic, strong) SEGRequestManager *reqManager;

@end

@implementation SEGAuthCodeView

- (instancetype)init {
    if (self = [super init]) {
        self.style = SEGAuthCodeViewRegisterStyle;
        self.frame = CGRectMake(0, 0, kScreenWidth, kLYScreenHeight());
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(notification_onKeyboardWillChangeFrame:)
                                                     name:UIKeyboardWillChangeFrameNotification
                                                   object:nil];
        [self createUI];
    }
    return self;
}

#pragma mark - Load Data
- (void)refreshCodeImg {
    // 【等保改造】验证码使用同一接口
    [self.reqManager requestSecurityRefreshCheckCodeWithFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed) {
            if ([self.reqManager.seg_segtelcaptchasbyregistermodel.imgCode length]>0) {
                NSData *_decodedImageData = [[NSData alloc] initWithBase64EncodedString:self.reqManager.seg_segtelcaptchasbyregistermodel.imgCode options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
                [self.codeImg setBackgroundImage:_decodedImage forState:UIControlStateNormal];
                [self clearText];
            }
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

- (void)createUI {
    self.bgView.frame = CGRectMake(50, 153, kScreenWidth-100, 244);
    [self addSubview:self.bgView];
    
    [self.bgView addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView).mas_offset(20);
        make.left.equalTo(self.bgView).mas_offset(50);
        make.right.equalTo(self.bgView).mas_offset(-50);
        make.height.mas_equalTo(15+18);
    }];
    [self.bgView addSubview:self.closeBtn];
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(self.bgView);
        make.height.width.mas_equalTo(42);
    }];
    [self.bgView addSubview:self.refreshBtn];
    [self.refreshBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLab.mas_bottom).mas_offset(20);
        make.right.equalTo(self.bgView).mas_offset(-50);
        make.width.height.mas_equalTo(50);
    }];
    [self.bgView addSubview:self.codeImg];
    [self.codeImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.refreshBtn);
        make.left.equalTo(self.bgView).mas_offset(50);
        make.right.equalTo(self.refreshBtn.mas_left);
        make.height.equalTo(self.refreshBtn);
    }];
    [self.bgView addSubview:self.line1];
    [self.line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeImg.mas_bottom).mas_offset(50);
        make.left.equalTo(self.bgView).mas_offset(50);
        make.right.equalTo(self.bgView).mas_offset(-50);
        make.height.mas_equalTo(0.5);
    }];
    [self.bgView addSubview:self.codeTF];
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.line1);
        make.height.mas_equalTo(19);
        make.bottom.equalTo(self.line1.mas_top).mas_offset(-15);
    }];
    [self.bgView addSubview:self.line2];
    [self.line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.bgView);
        make.height.mas_equalTo(0.5);
        make.bottom.equalTo(self.bgView.mas_bottom).mas_offset(-44);
    }];
    [self.bgView addSubview:self.nextBtn];
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line2.mas_bottom);
        make.left.right.equalTo(self.bgView);
        make.height.mas_equalTo(44);
    }];
}

- (void)clearText {
    self.codeTF.text = nil;
    self.nextBtn.enabled = NO;
}

#pragma mark - 键盘监听
- (void)notification_onKeyboardWillChangeFrame:(NSNotification *)aNotification {
    NSDictionary * userInfo = aNotification.userInfo;
    NSValue * keyBoardframeValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyBoardframe = keyBoardframeValue.CGRectValue;
    // 键盘消失
    if (LYScreenHeight() == keyBoardframe.origin.y) {
        // 视图居中
        CGFloat origin_y = ceil((keyBoardframe.origin.y-self.bgView.height)/2);
        CGRect frame = self.bgView.frame;
        frame.origin.y = origin_y;
        self.bgView.frame = frame;
        return;
    }
    // 背景距键盘顶部25pt
    CGFloat topMargin = ceil(self.bgView.bottom-keyBoardframe.origin.y+25);
    CGRect frame = self.bgView.frame;
    frame.origin.y -= topMargin;
    self.bgView.frame = frame;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self endEditing:YES];
    return YES;
}

#pragma mark - Event
- (void)closeButtonClick {
    [self dismiss];
}
- (void)nextButtonClick {
    if (self.style == SEGAuthCodeViewSecurityStyle) {
        if (self.confirmBlock) {
            self.confirmBlock(self.codeTF.text, self.reqManager.seg_segtelcaptchasbyregistermodel.randomToken);
        }
        return;
    }
    
    self.nextBtn.enabled = NO;
    // 校验验证码的正确性
    WeakSelf;
    [self.reqManager requestVerCodeForRegisterByRegister:self.phoneStr imgCode:self.codeTF.text randomToken:self.reqManager.seg_segtelcaptchasbyregistermodel.randomToken Finished:^(BOOL isSuccessed, id result, NSString* codeType, NSString* errorMessage) {
        weakSelf.nextBtn.enabled = NO;
        if (isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
            if ([self.delegate respondsToSelector:@selector(authCode_checkAuthCodeWithCode:randomToken:)]) {
                [self.delegate authCode_checkAuthCodeWithCode:self.codeTF.text randomToken:self.reqManager.seg_segtelcaptchasbyregistermodel.randomToken];
            }
            [weakSelf dismiss];
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            //接口失败 清空&刷新验证码
            [weakSelf refreshCodeImg];
            [weakSelf clearText];
        }
    }];
}

#pragma mark - Animation
- (void)show {
    self.hidden = NO;
    [self.codeTF becomeFirstResponder];
    [UIView animateWithDuration:0.2f animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7f];
        self.bgView.alpha = 1;
    } completion:^(BOOL finished) {
        [self refreshCodeImg];
    }];
}
- (void)dismiss {
    [self endEditing:YES];
    [UIView animateWithDuration:0.2f animations:^{
        self.backgroundColor = [UIColor clearColor];
        self.bgView.alpha = 0;
    } completion:^(BOOL finished) {
        self.hidden = YES;
        [self clearText];
    }];
}

#pragma mark - Getter
- (SEGRequestManager *)reqManager {
    if (!_reqManager) _reqManager = [[SEGRequestManager alloc] init];
    return _reqManager;
}
- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = kColor_W2;
        _bgView.layer.cornerRadius = 5;
        _bgView.layer.masksToBounds = YES;
    }
    return _bgView;
}
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.font = [UIFont boldSystemFontOfSize:16];
        _titleLab.textColor = kColor_1;
        _titleLab.textAlignment = NSTextAlignmentCenter;
        _titleLab.text = @"请输入图形验证码";
    }
    return _titleLab;
}
- (UIButton *)closeBtn {
    if (!_closeBtn) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_close_black")]
                   forState:UIControlStateNormal];
        [_closeBtn addTarget:self
                      action:@selector(closeButtonClick)
            forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}
- (UIButton *)refreshBtn {
    if (!_refreshBtn) {
        _refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_refreshBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_refresh")]
                     forState:UIControlStateNormal];
        [_refreshBtn addTarget:self
                        action:@selector(refreshCodeImg)
              forControlEvents:UIControlEventTouchUpInside];
    }
    return _refreshBtn;
}
- (UIButton *)codeImg {
    if (!_codeImg) {
        _codeImg = [UIButton buttonWithType:UIButtonTypeCustom];
        [_codeImg setBackgroundImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]
                            forState:UIControlStateNormal];
        [_codeImg addTarget:self
                     action:@selector(refreshCodeImg)
           forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeImg;
}
- (UIView *)line1 {
    if (!_line1) {
        _line1 = [[UIView alloc] init];
        _line1.backgroundColor = kColor_L4;
    }
    return _line1;
}
- (UITextField *)codeTF {
    if (!_codeTF) {
        _codeTF = [[UITextField alloc] init];
        _codeTF.font = kFont_18;
        [_codeTF setTextColor:kColor_1];
        _codeTF.tintColor = kColor_T;
        _codeTF.delegate = self;
        _codeTF.keyboardType = UIKeyboardTypeASCIICapable;
        _codeTF.textAlignment = NSTextAlignmentCenter;
        _codeTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _codeTF.autocorrectionType = UITextAutocorrectionTypeNo;
        [_codeTF configImgCodeInputLimitWithDelegate:self];
        WeakSelf;
        _codeTF.segTextDidChangeBlock = ^(NSString *text) {
            weakSelf.nextBtn.enabled = text.length > 0;
        };
    }
    return _codeTF;
}

- (UIView *)line2 {
    if (!_line2) {
        _line2 = [[UIView alloc] init];
        _line2.backgroundColor = kColor_L4;
    }
    return _line2;
}
- (UIButton *)nextBtn {
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setTitleColor:kColor_1
                       forState:UIControlStateNormal];
        [_nextBtn setTitleColor:kColor_C
                       forState:UIControlStateDisabled];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _nextBtn.titleLabel.font = kFont_16;
        [_nextBtn addTarget:self
                     action:@selector(nextButtonClick)
           forControlEvents:UIControlEventTouchUpInside];
        _nextBtn.enabled = NO;
    }
    return _nextBtn;
}

- (void)setStyle:(SEGAuthCodeViewStyle)style {
    _style = style;
    if (style == SEGAuthCodeViewSecurityStyle) {
        [self.nextBtn setTitle:@"确定" forState:UIControlStateNormal];
    }
}

- (BOOL)isShow {
    if (self.isHidden) {
        return NO;
    }
    return YES;
}

@end
